const app = getApp()
import { getBrowseHistoryList } from '../../../api/index'

Page({
  data: {
    list: [],
    currentPage: 1,
    pageSize: 15,
    keyword: ''
  },
  search ({ detail }) {
    this.setData({ keyword: detail })
    this.getList()
  },
  async loadMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize
      }
      if (this.data.keyword) query.materialName = this.data.keyword
      const { ResultSet } = await getBrowseHistoryList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.list.push(...ResultSet.userData.data)
        this.setData({
          list: this.data.list,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      console.log(err)
      this.loading = false
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getList () {
    try {
      wx.$pro.showLoading({ title: '加载中...', mask: true })
      let query = {
        currentPage: 1,
        pageSize: this.data.pageSize
      }
      if (this.data.keyword) query.materialName = this.data.keyword
      const { ResultSet } = await getBrowseHistoryList({ ...query })
      this.loading = false
      this.alloaded = false
      if (ResultSet.userData.data.length) this.data.currentPage = 2
      this.data.isEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      this.setData({
        currentPage: this.data.currentPage,
        list: ResultSet.userData.data,
        isEmpty: this.data.isEmpty
      })
      this.loading = false
      wx.$pro.hideLoading()
    } catch (err) {
      wx.$pro.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad () {
    this.getList()
  }
})